﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Hicap.AuthorizationServer.Application.Dto;
using Hicap.AuthorizationServer.Core.Managers;
using Hicap.AuthorizationServer.Core.Models;

namespace Hicap.AuthorizationServer.Application.Sys
{
    public class AuthObjectRoleRelatedAppService : AuthorizationServerApplicationBase<AuthObjectRoleRelated, AuthObjectRoleRelatedListDto, AuthObjectRoleRelatedEditDto>
    {
        private readonly IAuthObjectRoleRelatedManager _manager;

        public AuthObjectRoleRelatedAppService(IAuthObjectRoleRelatedManager manager
        ) : base(manager)
        {
            _manager = manager;
        }

        /// <summary>
        /// 按照固定条件查询关系表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<AuthObjectRoleRelatedListDto>> PagedQueryDatasAsync(AuthObjectRoleRelatedQueryDTO input)
        {
            //查询条件
            Func<AuthObjectRoleRelated, bool> query = (entity) =>
            {
                var flag = true;
                if (input.RoleId.HasValue) flag = entity.RoleId == input.RoleId && flag;
                if (input.AuthObjectId.HasValue) flag = entity.AuthObjectId == input.AuthObjectId && flag;
                if (!string.IsNullOrEmpty(input.AuthObjectCode)) flag = entity.AuthObject != null && (entity.AuthObject.ObjectCode == input.AuthObjectCode && flag);
                if (!string.IsNullOrEmpty(input.RoleCode)) flag = entity.Role != null && (entity.Role.RoleCode == input.RoleCode && flag);
                if (!string.IsNullOrEmpty(input.AuthObjectName)) flag = entity.AuthObject != null && (entity.AuthObject.ObjectName.Contains(input.AuthObjectName) && flag);
                if (!string.IsNullOrEmpty(input.RoleName)) flag = entity.Role != null && (entity.Role.RoleName.Contains(input.RoleName) && flag);
                return flag;
            };

            //记录数
            var count = await _manager.GetCount(query);

            //查询结果
            var result = await _manager.GetResult(query);

            //DTO Mapper
            var resultListDto = result.MapTo<List<AuthObjectRoleRelatedListDto>>();

            return new PagedResultDto<AuthObjectRoleRelatedListDto>(
                count,
                resultListDto
            );
        }
    }
}